﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace TcpClients
{
    class Program
    {
       private static TcpClient client = null;
        private static NetworkStream stream = null;
        static void Main(string[] args)
        {
            Console.Write("请输入服务器IP地址：");
            string strIp = Console.ReadLine();
            Console.Write("请输入服务器监听的端口号：");
            string strPort = Console.ReadLine();
            int port = Convert.ToInt32(strPort);
            Connect(strIp, port);//连接服务器
            do
            {
                Console.Write("发送消息：");
                string message = Console.ReadLine();
                SentAndReceived(message);
                if (Console.ReadLine().ToUpper() == "N") break;
            } while (true);
            if (stream != null) stream.Close();
            if (client != null) client.Close();
            Console.WriteLine("\n按任意键退出...");
            Console.Read();
        }

        /// <summary>
        /// 建立连接
        /// </summary>
        /// <param name="server">服务端地址</param>
        /// <param name="port">端口</param>
        private static void Connect(string server, int port)
        {
            try
            {
                client = new TcpClient(server, port);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        /// <summary>
        /// 信息发送
        /// </summary>
        /// <param name="message">信息内容</param>
        private static void SentAndReceived(string message)
        {
            Byte[] data = Encoding.UTF8.GetBytes(message);
            stream = client.GetStream();
            stream.Write(data, 0, data.Length);
            data = new Byte[1024];
            String responseData = String.Empty;
            int bytes = stream.Read(data, 0, data.Length);
            responseData = Encoding.UTF8.GetString(data, 0, bytes);
            Console.WriteLine("接收消息：{0}", responseData);
        }
    }
}
